/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Featured;
import org.cx1.model.Inquiry;
import org.cx1.model.Lead;
import org.cx1.model.Listing;
import org.cx1.model.User;
import org.cx1.model.utils.LeadComparator;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IFeaturedService;
import org.cx1.service.api.IInquiryService;
import org.cx1.service.api.ILeadService;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.IUserService;
import org.cx1.service.impl.DFeaturedService;
import org.cx1.service.impl.DLeadService;
import org.cx1.service.impl.DListingService;
import org.cx1.service.impl.DUserService;
import org.cx1.service.impl.MInquiryService;
import org.cx1.service.impl.MListingService;
import org.cx1.service.impl.MUserService;
import org.cx1.web.controller.action.AccountAction;
import org.cx1.web.controller.action.UserAction;
import org.cx1.web.utils.SessionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author ECH
 */
public class AccountController extends BaseController {
    
    //private IUserService userService = new MUserService();
    //private IListingService listingService = new MListingService();
    
    private IUserService userService = new DUserService();
    private IListingService listingService = new DListingService();
    private IFeaturedService featuredService = new DFeaturedService();
    private ILeadService leadService = new DLeadService();
    
    private IInquiryService inquiryService = new MInquiryService();
    
    public AccountController() {
    }
    
    protected ModelAndView handleRequestInternal( HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();        
        
        boolean loggedin = false;
        String userID = SessionUtils.getUserID(request.getSession());   
        
        if (!StringUtils.isEmpty(userID)) {
            loggedin = true;
            map.put("loggedin", loggedin);
        }
                
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        if (ServletFileUpload.isMultipartContent(request)) {
            parameterMap = this.getMultipartFormParams(request);
        } 
        else {
            parameterMap = this.getFormParams(request);
        }
        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        int action = StringUtils.isEmpty(formfields.get("a")) ? 0 : Integer.parseInt(formfields.get("a"));
        
        switch (action) {
            case AccountAction.UPDATE: {                      
                if (loggedin) {
                    update(mav, map, request);           
                }
                else {
                    mav.setView(new RedirectView("login.htm"));
                    return mav;                    
                }
                break;
            }
            default: {            
                if (loggedin) {
                    read(userID, mav, map, request);       
                }
                else {
                    mav.setView(new RedirectView("login.htm"));
                    return mav;                    
                }
                break;
            }
        }  
        
        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        map.put("props", this.getSystemProperties());
        mav.addObject("model", map);
        return mav;
    }
        
    private void read(String userID, ModelAndView mav, Map map, HttpServletRequest request) {
        ServiceResponse<User> response1 = this.userService.read(userID);
        ServiceResponse<List<Listing>> response2 = listingService.readUserListings(userID, 0, 0);
        ServiceResponse<List<Featured>> response4 = featuredService.readAll(0, 0);
        
        List<Listing> featuredListings = extractFeaturedListings(response2.getResponse(), response4.getResponse());
        List<Featured> userFeatureds = extractUserFeatureds(featuredListings, response4.getResponse());
        List<Lead> leads = leadService.readAll(0, 0).getResponse();        
        
        if (leads != null && leads.size() > 0) {
            Collections.sort(leads, new LeadComparator());
        }
        
        if (isThisRequestCommingFromAMobileDevice(request)) {
            mav.setViewName("account_mobile");
        }
        else {
            mav.setViewName("account");
        }
        
        map.put("listings", response2.getResponse()); 
        
        map.put("user", response1.getResponse());
        map.put("userFeatureds", userFeatureds);    
        
        map.put("showFeatured", 1);
        map.put("featuredListings", featuredListings); 
                 
        map.put("showLeads", checkLeadFeature(response2.getResponse()) ? 1 : 0);
        map.put("leads", leads);     
        
    }
        
    private void update(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {             
            String id = request.getParameter("id");    
            String userTypeID = request.getParameter("userTypeID");
            
            String brokerID = request.getParameter("brokerID");
            String gmailID = request.getParameter("gmailID");
            String yahooID = request.getParameter("yahooID");
            String facebookID = request.getParameter("facebookID");
            
            String email = request.getParameter("email");
            String password = request.getParameter("password");
                
            String firstName = StringUtils.isEmpty(request.getParameter("firstName")) ? "" : request.getParameter("firstName");
            String lastName = StringUtils.isEmpty(request.getParameter("lastName")) ? "" : request.getParameter("lastName");
                
            String name = request.getParameter("name");
                
            String title = request.getParameter("title");            
            String description = request.getParameter("description");            
            String notes = request.getParameter("notes");
                        
            String mobilePrimary = request.getParameter("mobilePrimary");            
            String landlinePrimary = request.getParameter("landlinePrimary");
            
            String primaryPhotoID = request.getParameter("primaryPhotoID");            
            String photoIDs = request.getParameter("photoIDs");        
            
            String contactIDs = request.getParameter("contactIDs");            
            String companyIDs = request.getParameter("companyIDs");
                        
            ServiceResponse<User> response1 = userService.read(id);              
            User user = response1.getResponse();          

            if (user != null) {
                user.setUserTypeID(userTypeID);
            
                user.setBrokerID(brokerID);
                user.setGmailID(gmailID);
                user.setYahooID(yahooID);
                user.setFacebookID(facebookID);

                user.setEmail(email);
                user.setPassword(password);

                user.setFirstName(firstName);
                user.setLastName(lastName);
                
                user.setName(name);

                user.setTitle(title);
                user.setDescription(description);
                user.setNotes(notes);

                user.setPrimaryPhotoID(primaryPhotoID);
                user.setPhotoIDs(StringUtils.isEmpty(photoIDs) ? null : Arrays.asList(photoIDs.split("\\s*,\\s*")));

                user.setMobilePrimary(mobilePrimary);
                user.setLandlinePrimary(landlinePrimary);
                
                user.setContactIDs(StringUtils.isEmpty(contactIDs) ? null : Arrays.asList(contactIDs.split("\\s*,\\s*")));
                user.setCompanyIDs(StringUtils.isEmpty(companyIDs) ? null : Arrays.asList(companyIDs.split("\\s*,\\s*")));
                
                ServiceResponse<Boolean> response = userService.update(user);
                map.put("user", response.getResponse());
                mav.setView(new RedirectView("user.htm?a="+UserAction.READ+"&id="+id));
            }
            else {
                mav.setView(new RedirectView("user.htm"));                
            }
            
            ServiceResponse<Boolean> response = userService.update(user);
            map.put("user", response.getResponse());
            mav.setView(new RedirectView("account.htm?a="+AccountAction.READ+"&id="+id));
        }        
        else {                  
            String id = request.getParameter("id");    
            ServiceResponse<User> response = userService.read(id);
            map.put("user", response.getResponse());
            
            if (isThisRequestCommingFromAMobileDevice(request)) {
                mav.setViewName("accountedit_mobile");
            }
            else {
                mav.setViewName("accountedit");                
            }
        }
    }
    
    private List<Listing> extractFeaturedListings(List<Listing> listings, List<Featured> featureds) {
        List<Listing> featuredListing = new ArrayList<Listing>();
        try {            
            if (listings != null && listings.size() > 0 && featureds!= null && featureds.size() > 0) {
                for (Listing listing : listings) {
                    for (Featured featured : featureds) {
                        if (StringUtils.equalsIgnoreCase(featured.getListingID(), listing.getId())) {
                            featuredListing.add(listing);
                            break;
                        }
                    }
                }
            }
        }
        catch (Exception ex) { ex.printStackTrace(); }
        return featuredListing;
    }
    
    private List<Featured> extractUserFeatureds(List<Listing> featuredListings, List<Featured> featureds) {
        List<Featured> userFeatureds = new ArrayList<Featured>();
        try {
            if (featuredListings != null && featuredListings.size() > 0 && featureds != null && featureds.size() > 0) {
                for (Listing listing : featuredListings) {
                    for (Featured featured : featureds) {
                        
                        if (StringUtils.equalsIgnoreCase(featured.getListingID(), listing.getId())) {
                            
                            featured.setListingTitle(listing.getTitle());
                            featured.setListingPrimaryPhoto(listing.getPrimaryPhoto());
                            featured.setDisplayCity(featured.getCity());
                            featured.setDisplayCityURL(featured.getCity().trim().toLowerCase());
                            featured.setDisplayTerm(StringUtils.equalsIgnoreCase("1", featured.getTermType().trim()) ? "Long Term Rentals" : "Short Term Rentals");
                            featured.setDisplayTermURL(StringUtils.equalsIgnoreCase("1", featured.getTermType().trim()) ? "long-term-rentals" : "short-term-rentals");
                            userFeatureds.add(featured);
                        }
                    }
                }
            }
        } 
        catch (Exception ex) { ex.printStackTrace(); }
        return userFeatureds;
    }
     
    
    private boolean checkLeadFeature(List<Listing> listings) {
        boolean approve = false;
        
        int ctr = 0;        
        if (listings != null && listings.size() > 0) {
            for (Listing listing : listings) {
                if (listing.isVerified() && listing.isPosted() && !listing.isPenalized()) {
                    ctr++;
                }
            }
        }
        
        if (ctr >= 5) {
            approve = true;
        }        
        return approve;
    }
    
}